package com.shujia

import scala.io.Source

object Demo29Top10 {
  def main(args: Array[String]): Unit = {

    /**
      * 统计年级排名前十学生各科的分数 [学号,学生姓名，学生班级，科目名，分数]
      *
      */

    val scores: List[String] = Source.fromFile("scala/data/score.txt").getLines().toList

    //将学号和分数取出来
    val kvScore: List[(String, Int)] = scores.map(line => {

      val split: Array[String] = line.split(",")
      val id: String = split(0)
      val score: Int = split(2).toInt

      //返回元组
      (id, score)
    })

    //统计学生总分
    //groupBy  通过什么来分组

    //通过学号分组
    val map: List[(String, List[(String, Int)])] = kvScore.groupBy(kv => kv._1).toList

    val sumScores: List[(String, Int)] = map.map(kv => {
      val id: String = kv._1

      //取出分组
      val scos: List[Int] = kv._2.map(kkv => kkv._2)
      //统计总分
      val sumSco: Int = scos.sum

      (id, sumSco)
    })

    //排序取前十
    val tuples: List[(String, Int)] = sumScores.sortBy(kv => -kv._2).take(10)

    //去掉总分
    val ids: List[String] = tuples.map(kv => kv._1)


    //取出前十学生的分数
    val topScores: List[String] = scores.filter(line => {
      val id: String = line.split(",")(0)

      ids.contains(id)
    })
    //关联学生表和科目表

    val students: List[String] = Source.fromFile("scala/data/students.txt").getLines().toList
    val cources: List[String] = Source.fromFile("scala/data/cource.txt").getLines().toList


    /**
      * 将学生表和科目表转换成map集合
      *
      */

    val stuMap: Map[String, String] = students.map(line => {
      val id: String = line.split(",")(0)
      (id, line)
    }).toMap // 学号作为key,学生信息作为value的map集合


    val couMap: Map[String, String] = cources.map(line => {
      val cId: String = line.split(",")(0)
      (cId, line)
    }).toMap // 科目编号作为key,科目信息作为value的map集合


    //表关联
    val result: List[String] = topScores.map(line => {
      val split: Array[String] = line.split(",")
      val sId: String = split(0)
      val cId: String = split(1)
      val sco: Int = split(2).toInt

      //通过学号去学生表的map中取出学生的信息

      val stuInfo: String = stuMap.getOrElse(sId, "")

      val couInfo: String = couMap.getOrElse(cId, "")


      //整理数据格式
      s"$stuInfo,$couInfo,$sco"
    })

    result.foreach(println)


  }
}
